<template>
  <a-card :bordered='false' style='width: 100%'>
    <search :config='searchConfig' @search='search' @getHeight='getHeight' />
    <!-- 操作按钮区域 -->
    <div class='table-operator' style='border-top: 5px'>
      <a-button @click='handleAdd' type='primary'>新增</a-button>
      <a-button @click='' type='primary'>删除</a-button>
      <a-button type='primary'  @click="downExportXls('user_service')">导出</a-button>
      <a-button type='primary'  @click="handleExportXls('用户模版')">模板下载</a-button>
      <a-upload
        name='file'
        :showUploadList='false'
        :multiple='false'
        :headers='tokenHeader1'
        :action='importExcelUrl'
        @change='handleImportExcel'
      >
        <a-button type='primary' >导入</a-button>
      </a-upload>
      <a-button type='primary' :disabled='selectedRowKeys.length<=0' @click='uboundOpenId'>微信解绑</a-button>
      <!--            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"-->
      <!--                      @change="handleImportExcel">-->
      <!--                <a-button type="primary" icon="import">导入</a-button>-->
      <!--            </a-upload>-->
      <!--                  <a-button type="primary" icon="hdd" @click="recycleBinVisible=true">回收站</a-button>-->
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay' @click='handleMenuClick'>
          <a-menu-item key='1'>
            <a-icon type='lock' @click="batchFrozen('003')" />
            冻结
          </a-menu-item>
          <a-menu-item key='2'>
            <a-icon type='unlock' @click="batchFrozen('009')" />
            解冻
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'>
          批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
<!--      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>-->
<!--        <i class='anticon anticon-info-circle ant-alert-icon'></i>已选择&nbsp;<a-->
<!--        style='font-weight: 600'>{{ selectedRowKeys.length-->
<!--        }}</a>项&nbsp;&nbsp;-->
<!--        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>-->
<!--        <span style='float:right;'>-->
<!--                      <a @click='loadData()'><a-icon type='sync' />刷新</a>-->
<!--                      </span>-->
<!--      </div>-->

      <a-table
        :scroll='{x:1250,y:pageHeight-86-220}'
        ref='table'
        size='middle'
        class='Table'
        bordered
        rowKey='id'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='ipagination'
        :customRow='onClickRow'
        :loading='loading'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='handleTableChange'>
        <div slot='avatarslot' slot-scope='text, record, index'>
          <div class='anty-img-wrap'>
            <a-avatar shape='square' :src='getAvatarView(record.avatar)' icon='user' />
          </div>
        </div>
        <template slot='roleCode' slot-scope='text,record'>
          {{ text == 'null' ? '#' : text }}
        </template>
        <span slot='action' slot-scope='text, record'>
          <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a-dropdown>
            <a class='ant-dropdown-link'>
              更多 <a-icon type='down' />
            </a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a href='javascript:;' @click='handleDetail(record)'>详情</a>
              </a-menu-item>
              <a-menu-item>
                <a href='javascript:;' @click='handleConfig(record)'>用户配置</a>
              </a-menu-item><a-menu-item>
                <a href='javascript:;' @click='handleChangePassword(record.userName)'>密码</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
              <!--              <a-menu-item v-if="record.status==1">-->
              <!--                <a-popconfirm title="确定冻结吗?" @confirm="() => handleFrozen(record.id,2,record.userName)">-->
              <!--                  <a>冻结</a>-->
              <!--                </a-popconfirm>-->
              <!--              </a-menu-item>-->

              <!--              <a-menu-item v-if="record.status==2">-->
              <!--                <a-popconfirm title="确定解冻吗?" @confirm="() => handleFrozen(record.id,1,record.userName)">-->
              <!--                  <a>解冻</a>-->
              <!--                </a-popconfirm>-->
              <!--              </a-menu-item>-->

              <!--              <a-menu-item>-->
              <!--                <a href="javascript:;" @click="handleAgentSettings(record.userName)">代理人</a>-->
              <!--              </a-menu-item>-->

            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <user-modal ref='modalForm' @ok='modalFormOk'></user-modal>

    <password-modal ref='passwordmodal' @ok='passwordModalOk'></password-modal>

    <sys-user-agent-modal ref='sysUserAgentModal'></sys-user-agent-modal>

    <!-- 用户回收站 -->
    <user-recycle-bin-modal :visible.sync='recycleBinVisible' @ok='modalFormOk' />

    <ConfigModal ref='ConfigModal' @ok='saveUserRelation'></ConfigModal>
  </a-card>
</template>

<script>
import UserModal from '@page-modules/UserModal'
import ConfigModal from '@page-modules/ConfigModal'
import PasswordModal from '@page-modules/PasswordModal'
import { getAction, postAction, putAction, getFileAccessHttpUrl } from '@/api/manage'
import { frozenBatch, queryDepartTreeList } from '@/api/api'
import { PageListMixin } from '@/mixins/PageListMixin'
import SysUserAgentModal from '@page-modules/SysUserAgentModal'
import JInput from '@/components/cn-form/JInput'
import UserRecycleBinModal from '@page-modules/UserRecycleBinModal'
import CnDictSelectTag from '@/components/dict/CnDictSelectTag'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  name: 'UserList',
  mixins: [PageListMixin],
  components: {
    SysUserAgentModal,
    UserModal,
    PasswordModal,
    JInput,
    UserRecycleBinModal,
    ConfigModal,
    CnDictSelectTag
  },
  data() {
    return {
      tokenHeader1: { 'loginUserToken': Vue.ls.get(ACCESS_TOKEN) },
      treeData: [],
      description: '这是用户管理页面',
      queryParam: {},
      recycleBinVisible: false,
      searchConfig: [
        {
          type: 'input',
          name: 'userName',
          placeholder: '请输入账号查询'
        }, {
          type: 'input',
          name: 'realName',
          placeholder: '请输入真实姓名'
        }, {
          type: 'input',
          name: 'roleCode',
          placeholder: '请输入角色名称'
        },
        {
          type: 'tree-select',
          name: 'orgCode',
          dataType: 'org',
          placeholder: '请选择组织'
        },
        {
          type: 'j-select',
          name: 'userType',
          dictCode: 'user_type',
          placeholder: '请选择用户类型'
        }
      ],
      columns: [
        {
          title: '用户账号',
          align: 'left',
          dataIndex: 'userName',
          width: 100,
          // sorter: true
          // fixed:true,
        },
        {
          title: '用户名称',
          align: 'left',
          width: 150,
          dataIndex: 'realName',
        },
        {
          title: '部门',
          align: 'left',
          width: 100,
          dataIndex: 'departName'
        },
        {
          title: '用户类型',
          align: 'left',
          width: 100,
          dataIndex: 'userType_dictText'
        },
        {
          title: 'OA账号',
          align: 'left',
          dataIndex: 'jobNum',
          width: 100,
          // sorter: true
        },
        {
          title: '角色',
          align: 'left',
          width: 100,
          dataIndex: 'roleNames',
          scopedSlots: { customRender: 'roleCode' }
        },
        {
          title: '状态',
          align: 'left',
          width: 70,
          dataIndex: 'status',
          customRender: (r, t, index) => {
            let vm = this
            let child = (r=='1'?'启用':'停用')
            const obj = {
              children: child,
              attrs: {}
            }
            return obj
          }
        },
        {
          title: '创建人',
          align: 'left',
          width: 70,
          dataIndex: 'createName'
        },
        {
          title: '创建时间',
          align: 'left',
          dataIndex: 'createTime'
        },
        {
          title: '更新人',
          align: 'left',
          width: 70,
          dataIndex: 'updateName'
        },
        {
          title: '更新时间',
          align: 'left',
          dataIndex: 'updateTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
          align: 'left',
          width: 150
        }

      ],
      isorter:{
        // userType:'1',
      },
      url: {
        syncUser: '/process/extActProcess/doSyncUser',
        list: window._CONFIG['domianURL'] + '/cnUserController/getPageList',
        delete: window._CONFIG['domianURL'] + '/cnUserController/deleteByid',
        detail:window._CONFIG['domianURL'] + '/cnUserController/getUserByIdOrCode',
        exportXlsUrl: window._CONFIG['domianURL'] + '/cnUserController/downloadTemplate',
        importExcelUrl: '/cnUserController/importTemplate',
        saveUserRelation: window._CONFIG['domianURL'] + '/cnUserController/saveUserRelation',
        openid: window._CONFIG['domianURL'] + '/cnUserController/uboundOpenIdByUser'
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    loadTree() {
      var that = this
      queryDepartTreeList().then((res) => {
        if (res.success) {
          that.treeData = []
          let treeList = res.result
          for (let a = 0; a < treeList.length; a++) {
            let temp = treeList[a]
            temp.isLeaf = temp.leaf
            that.treeData.push(temp)
          }
        }
      })
    },
    saveUserRelation(params) {
      postAction(this.url.saveUserRelation, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigModal.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigModal.confirmLoading = false
        //that.close();
      })
    },
    getAvatarView: function(avatar) {
      return getFileAccessHttpUrl(avatar)
    },

    batchFrozen: function(status) {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return false
      } else {
        let ids = ''
        let that = this
        let isAdmin = false
        that.selectionRows.forEach(function(row) {
          if (row.userName == 'admin') {
            isAdmin = true
          }
        })
        if (isAdmin) {
          that.$message.warning('管理员账号不允许此操作,请重新选择！')
          return
        }
        that.selectedRowKeys.forEach(function(val) {
          ids += val + ','
        })
        that.$confirm({
          title: '确认操作',
          content: '是否' + (status == '009' ? '解冻' : '冻结') + '选中账号?',
          onOk: function() {
            frozenBatch({ ids: ids, status: status }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    handleMenuClick(e) {
      if (e.key == 1) {
        this.batchFrozen('003')
      } else if (e.key == 2) {
        this.batchFrozen('009')
      }
    },
    handleFrozen: function(id, status, userName) {
      let that = this
      //TODO 后台校验管理员角色
      if ('admin' == userName) {
        that.$message.warning('管理员账号不允许此操作！')
        return
      }
      frozenBatch({ ids: id, status: status }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleChangePassword(userName) {
      this.$refs.passwordmodal.show(userName)
    },
    handleAgentSettings(userName) {
      this.$refs.sysUserAgentModal.agentSettings(userName)
      this.$refs.sysUserAgentModal.title = '用户代理人设置'
    },
    passwordModalOk() {
      //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
    },
    uboundOpenId() {
      let ids = this.selectedRowKeys + ''
      getAction(this.url.openid, { ids }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    }
  },
  created() {
    this.loadTree()
  }

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>

